var io = require('socket.io');
var http = require("http");
var url = require('url');
var qs = require('querystring');
var config = require('config');
var host = config.get('host');
var map = {};

var server = http.createServer(function (req, res) {
    if (!isValid(url.parse(req.url).pathname)) {
        res.writeHead(404, {'Content-Type': 'text/plain;charset=utf-8'});
        res.write("{'errcode':404,'errmsg':'请求不在定义范围内'}");
        res.end();
    } else {
        res.writeHead(200, {'Content-Type': 'text/plain;charset=utf-8'});
        if (req.method.toUpperCase() == 'POST') {
            var postData = "";
            req.addListener("data", function (data) {
                postData += data;
            });
            req.addListener("end", function () {
                var query = qs.parse(postData);
                var str = JSON.stringify(query);
                var obj = JSON.parse(str);
                if (url.parse(req.url).pathname == "/message_push") {
                    if (obj.message != "") {
                        writeOutClient(query);
                    }
                    writeOut(query, res);
                }
                if (url.parse(req.url).pathname == "/is_cover/push") {
                    writeOutClientIsCover(query, res);
                }
            });
        }
    }
});
server.listen(5001,host);
sockets = io.listen(server);

var route = {
    '/': "/",
    '/message_push': '/message_push',
    '/is_cover/push': '/is_cover/push'
};

var isValid = function (reqPath) {
    for (var key in route) {
        if (route[key] == reqPath) {
            return true;
        }
    }
    return false;
};

var writeOut = function (query, res) {
    var str = JSON.stringify(query);
    var obj = JSON.parse(str);
    var socket = map[obj.adminId];
    if (typeof(socket) != "undefined") {
        socket.emit('message_push',{
          data: JSON.stringify(query)
        });
    }
    res.end();
}

var writeOutClient = function (query, res) {
    sockets.emit('message_push_client',{
      data: JSON.stringify(query)
    });
}

var writeOutClientIsCover = function (query, res) {
    sockets.emit('message_push_client_is_cover',{
      data: JSON.stringify(query)
    });
    res.end();
}

sockets.on('connection', function (socket) {
     var socketId = socket.id;

     socket.on('join', function (data) {
        map[data.adminId] = socket;
     });

     socket.on('disconnect', function () {
     });

});